/**
 * 北京中流科技有限公司 版权所有
 * http://www.chinasoa.com.cn
 */
package cn.com.chinasoa.course.subscribe.util;

import java.util.Properties;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

/**
 * @author 刘洋(liuyang@chinasoa.com.cn)
 * 2007-9-26下午08:53:09
 */
public class EntityManagerHelper {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		EntityManager em = EntityManagerHelper.getEntityManager();
		em.getTransaction().begin();
		em.getTransaction().commit();
		EntityManagerHelper.closeEntityManager();
	}

	public static final Properties jpaProperties = new Properties();
	public static final EntityManagerFactory tEntityManagerFactory=Persistence.createEntityManagerFactory("train",jpaProperties);
	public static final ThreadLocal<EntityManager> tThreadLocal = new ThreadLocal<EntityManager>();

	public static EntityManager getEntityManager(){
		EntityManager tEntityManager = (EntityManager) tThreadLocal.get();
	    if (tEntityManager == null) {
	    	tEntityManager = tEntityManagerFactory.createEntityManager();
	    	tThreadLocal.set(tEntityManager);
	    }
	    return tEntityManager;
	}

	public static void closeEntityManager(){
		EntityManager tEntityManager = (EntityManager) tThreadLocal.get();
	    if (tEntityManager != null)tEntityManager.close();
	    tThreadLocal.set(null);
	}
}
